<template>
  <div class="filter-container">
    <div style="margin-left: 20px;margin-top: 10px;float: left">
      <div style="float: left">
        <el-input v-model="dataForm.demoname" size="medium" placeholder="请输入计划名称" style="width: 200px;" class="filter-item" @keyup.native="handleFilter" />
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button size="medium" type="primary" icon="el-icon-edit" @click="createHandle">新增计划</el-button>
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button size="medium" type="danger" @click="batchHandle">批量删除</el-button>
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button size="medium" type="success" icon="el-icon-download" @click="exportexcel">导出</el-button>
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshTable">
          刷新
        </el-button>
      </div>
    </div>
    <el-table
      ref="dataTable"
      border
      highlight-current-row
      :data="pageData"
      style="width: 98%;left: 1.5%;"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="plan_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="计划名称"
        min-width="120"
      />
      <el-table-column
        prop="testset_num"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="用例集"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-link v-if="scope.row.testset_num === '' " type="primary" :underline="false"><el-tag class="step-count" @click="runHandle(scope.row)">0</el-tag></el-link>
          <el-link v-else type="primary" :underline="false"><el-tag class="step-count" @click="runHandle(scope.row)">{{ scope.row.testset_num }}</el-tag></el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="executor_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="执行机/组"
        min-width="120"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.executor_name !== '' ">{{ scope.row.executor_name }}</span>
          <span v-else>{{ scope.row.executor_group_name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="parallel"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="并发"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.parallel === 1" size="small">是</el-tag>
          <el-tag v-else size="small" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="exec_config_plan"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="执行配置"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-button type="primary" @click="Performconfig(scope.row)">配置</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="cron_express"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="执行时间"
        min-width="120"
      />
      <el-table-column
        prop="status"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="任务状态"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" size="small">开启</el-tag>
          <el-tag v-else size="small" type="danger">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="创建时间"
        min-width="120"
      />
      <el-table-column
        prop="creator_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="创建人"
        min-width="120"
      />
      <el-table-column
        prop="last_alter_time"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="修改时间"
        min-width="120"
      />
      <el-table-column
        prop="last_mender_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="修改人"
        min-width="120"
      />
      <el-table-column
        prop="mark"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="备注"
        min-width="120"
      />
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="160">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateHandle(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="run(scope.row)">执行</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="margin-left: 1.5%;">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--配置-->
    <el-dialog title="配置" :visible.sync="Performconfigvisible">
      <el-form ref="dataForm" :rules="rules" :model="PerformOK.exec_config_plan" label-position="left" label-width="190px" style=" margin-left:15%;">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="浏览器：" prop="browser">
              <el-select v-model="PerformOK.exec_config_plan.browserName" clearable placeholder="请选择" style="width: 200px">
                <el-option
                  v-for="item in value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="元素定位超时时间(秒)：" prop="findElementTimeout">
              <el-input v-model="PerformOK.exec_config_plan.findElementTimeout" style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="页面加载超时时间(秒)：" prop="pageLoadTimeout">
              <el-input v-model="PerformOK.exec_config_plan.pageLoadTimeout" style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="24" :class="[ hidePlanDataFlag ? 'hide-data' : '' ]">
            <el-form-item label="测试数据" prop="testdata_plan" class="test-data-row">
              <el-row v-for="(item, index) in PerformOK.testdata_plan" :key="index">
                <el-col :span="10">
                  <el-input v-model="item.plan_key" />
                </el-col>
                <el-col :span="10" style="margin-left: 4px;">
                  <el-input v-model="item.plan_value" />
                </el-col>
                <i class="el-icon-delete" style="cursor: pointer;margin-left: 4px;" @click="deleteItem(item, index)" />
                <i class="el-icon-plus" style="cursor: pointer;" @click="addItem" />
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-col :span="24">
        <vue-json-editor v-model="PerformOK.testdata_plan" lang="zh" :mode="'code'" />
      </el-col>
      <div style="text-align: center">
        <el-button @click="Performconfigvisible=false">取 消</el-button>
        <el-button type="warning" @click="hideOrShowPlanTestData">{{ hidePlanDataFlag ? '显示' : '隐藏' }}测试数据</el-button>
        <el-button type="primary" @click="PerformconfigOK">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增/编辑-->
    <add-or-update v-if="AddOrUpdateV" :teslt-plan-item="TesltPlanItem" :title="edit.textMap[edit.status]" @closeDialog="closeDialog" />
  </div>
</template>

<script>
import { testplenList, delNode, updateEdit, runHandle } from '@/api/testplan'
import mixinBaseView from '@/mixins/view-base.js'
import AddOrUpdate from './components/TestPlanAddUpdate'
import vueJsonEditor from 'vue-json-editor'
export default {
  components: {
    AddOrUpdate,
    vueJsonEditor
  },
  mixins: [mixinBaseView],
  data() {
    return {
      // 隐藏测试数据
      hidePlanDataFlag: false,
      // 配置窗口
      Performconfigvisible: false,
      // 表单数据
      tableData: [],
      // 添加/编辑窗口
      AddOrUpdateV: false,
      // 用例集窗口
      UseCasesSetV: false,
      // 设置名称
      commonPageSetting: {
        entityTitle: '测试计划' // 当前页面的对象名称
      },
      // 搜索条件
      dataForm: {
        demoname: ''
      },

      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      totalPage: 0,
      edit: {
        status: '',
        textMap: {
          update: '编辑测试计划',
          create: '新增测试计划'
        }
      },
      // 新增/编辑参数
      TesltPlanItem: {
        id: '',
        plan_name: '',
        parallel: '',
        cron_express: '',
        executor_group_id: '',
        executor_id: '',
        exec_config_plan: {
          browserName: '',
          findElementTimeout: '',
          pageLoadTimeout: ''
        },
        testdata_plan: {},
        plan_key: '',
        plan_value: '',
        expire_time: '',
        status: '',
        mark: ''
      },
      // 配置参数
      value: [{
        value: 'chrome',
        label: 'chrome'
      }, {
        value: 'ie',
        label: 'ie'
      }, {
        value: 'firefox',
        label: 'firefox'
      }],
      PerformOK: {
        testdata_plan: [],
        exec_config_plan: {
          browserName: '',
          findElementTimeout: '',
          pageLoadTimeout: ''
        },
        id: ''
      },
      rules: {
        findElementTimeout: [{ required: true, message: '请输入元素定位超时时间(秒)', trigger: 'change' }],
        pageLoadTimeout: [{ required: true, message: '请输入页面加载超时时间(秒)', trigger: 'change' }],
        browserName: [{ required: true, message: '请选择浏览器', trigger: 'change' }]

      }

    }
  },
  computed: {
    // 总数
    total() {
      return this.tableData.length
    },
    // 当前分页数据
    pageData() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  mounted() {
    this.getData()
  },

  methods: {
    deleteItem(item, index) {
      this.PerformOK.testdata_plan.splice(index, 1)
      if (this.PerformOK.testdata_plan.length === 0) {
        this.addItem()
      }
    },
    // 动态表单
    addItem() {
      this.PerformOK.testdata_plan.push({
        plan_key: '',
        plan_value: ''
      })
    },
    // 表格排序
    tableSortChange({ column, prop, order }) {
      if (order === null) {
        this.handleFilter()
        return false
      }
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    // 条件查询
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = this.selfHandleFilter(data)
    },
    // 详细的过滤操作，需要覆写此方法
    selfHandleFilter(data) {
      if (this.dataForm.demoname !== '') {
        data = data.filter(item => item.plan_name.indexOf(this.dataForm.demoname) !== -1)
      }
      if (this.dataForm.demoname === '') {
        this.getData()
      }
      return data
    },
    selectRowHandle(selection) {
      this.selectIds = []
      this.selectmapIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectmapIds.push(row.map_id)
        self.selectIds.push(row.id)
      })
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 新增
    createHandle() {
      this.TesltPlanItem = {
        id: '',
        plan_name: '',
        parallel: '',
        cron_express: '',
        executor_group_id: '',
        executor_id: '',
        exec_config_plan: {
          browserName: '',
          findElementTimeout: '',
          pageLoadTimeout: ''
        },
        testdata_plan: {},
        expire_time: '',
        status: '',
        mark: ''
      }
      this.AddOrUpdateV = true
      this.edit.status = 'create'
    },
    runHandle(row) {
      this.$router.push({
        path: '/testPlan/TestUseCasesSet',
        query: {
          id: row.id,
          planName: row.plan_name
        }
      })
    },
    // 关闭操作
    closeDialog(flag) {
      if (flag) {
        this.getData()
      }
      this.AddOrUpdateV = false
    },
    // 批量操作
    batchHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      let successCount = 0
      let failCount = 0
      const self = this
      this.$confirm('是否批量删除选择的共 ' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectIds.forEach(function(val) {
          delNode({ id: val }).then(response => {
            successCount++
          }).catch(() => {
            failCount++
          })
        })

        const intervalId = setInterval(function() {
          if ((successCount + failCount) === self.selectIds.length) {
            clearInterval(intervalId)
            self.getData()
            self.$alert('本次共删除成功 ' + successCount + ' 条数据, 删除失败 ' + failCount + ' 条数据!', '提示')
          }
        }, 300)
      }).catch()
    },
    // 获取数据
    getData() {
      const params = {}
      testplenList(params).then(response => {
        this.tableData = response.data
      })
    },
    // 删除
    deleteHandle(row) {
      this.$confirm('是否删除' + this.commonPageSetting.entityTitle + ' 【' + row.plan_name + '】 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delNode({ id: row.id }).then(response => {
          this.getData()
          this.$message.success('删除成功')
        })
      }).catch(() => {
      })
    },
    // 更新
    updateHandle(row) {
      this.AddOrUpdateV = true
      this.edit.status = 'update'
      Object.assign(this.TesltPlanItem, row)
      this.TesltPlanItem.exec_config_plan = JSON.parse(row.exec_config_plan)
      return
    },
    // 执行配置
    Performconfig(row) {
      this.hidePlanDataFlag = false
      this.PerformOK.testdata_plan = []
      const n = []
      this.Performconfigvisible = true
      this.PerformOK.id = row.id
      this.PerformOK.exec_config_plan = JSON.parse('{"Perform":[' + row.exec_config_plan + ']}').Perform[0]
      if (row.testdata_plan !== {} && row.testdata_plan.length !== 0) {
        for (const key in JSON.parse(row.testdata_plan)) {
          n.push({
            key: key,
            value: JSON.parse(row.testdata_plan)[key]
          })
        }
        for (let i = 0; i < n.length; i++) {
          this.PerformOK.testdata_plan.push({
            plan_key: n[i].key,
            plan_value: n[i].value
          })
        }
      }
      if (this.PerformOK.testdata_plan.length === 0) {
        this.addItem()
      }
    },
    // 更新配置
    PerformconfigOK() {
      const n = {}
      this.$refs.dataForm.validate((validate) => {
        if (validate) {
          this.Performconfigvisible = false
          for (let i = 0; i < this.PerformOK.testdata_plan.length; i++) {
            if (this.PerformOK.testdata_plan[i].plan_key !== undefined && this.PerformOK.testdata_plan[i].plan_key.length > 0) {
              n[this.PerformOK.testdata_plan[i].plan_key] = this.PerformOK.testdata_plan[i].plan_value
            }
          }
          this.PerformOK.testdata_plan = JSON.stringify(n)
          updateEdit(this.PerformOK).then(response => {
            this.$message.success('更新配置成功')
            this.getData()
          })
        } else {
          this.$message.error('更新配置失败')
        }
      })
    },
    // 收起测试数据
    hideOrShowPlanTestData() {
      this.hidePlanDataFlag = !this.hidePlanDataFlag
    },
    // 导出
    exportexcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')

        const tHeader = ['序号', '计划名称', '用例集', '执行机/组', '并发', '执行配置', '执行时间', '任务状态', '创建时间', '创建人', '修改时间', '修改人', '备注', '操作']// 上面设置Excel的表格第一行的标题

        const filterVal = ['id', 'plan_name', 'testset_num', 'executor_name', 'parallel', 'exec_config_plan', 'cron_express', 'status', 'create_time', 'creator_name', 'last_alter_time', 'last_mender_name', 'mark'] // 上面的index、nickName、name是tableData里对象的属性

        const list = this.tableData // 把data里的tableData存到list

        for (var i = 0; i < list.length; i++) {
          if (list[i].parallel === 1) {
            list[i].parallel = '是'
          } else {
            list[i].parallel = '否'
          }
          if (list[i].status === 1) {
            list[i].status = '开启'
          } else {
            list[i].status = '关闭'
          }
          list[i].exec_config_plan = '配置'
        }
        const data = this.formatJson(filterVal, list)

        export_json_to_excel(tHeader, data, '测试计划') // 标题，数据，文件名
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 执行
    run(row) {
      if (row.testset_num > 0) {
        this.$confirm('是否执行' + this.commonPageSetting.entityTitle + ' 【' + row.plan_name + '】 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          runHandle({ plan_id: row.id }).then(response => {
            this.$message.success('执行成功')
            this.getData()
          })
        })
      } else {
        this.$message.error('请添加用例集')
      }
    }
  }
}
</script>

<style scoped>
  /deep/ .jsoneditor-vue{
    height:260px;
    margin-left: 2%;
    margin-right: 2%;
    margin-bottom: 10px;
  }
  .test-data-row .el-row+.el-row {
    margin-top: 10px;
  }
  .hide-data {
    display: none;
  }
</style>
